// ******************************COPYRIGHT NOTICE*******************************
// All rights reserved. This material is confidential and proprietary to
// CogentSoft (Shen Zhen) Limited and no part of this material should be
// reproduced,
// published in any form by any means, electronic or mechanical including
// photocopy or any information storage or retrieval system nor should the
// material be disclosed to third parties without the express written
// authorization of CogentSoft (Shen Zhen) Limited.
/*
 * <PRE> ******************************PROGRAM
 * DESCRIPTION***************************** Program Name : HtmlUtil.java
 * Description: HtmlUtil object Creation Date : 2006-5-29 Creator: 开发组
 * ******************************************************************************
 * </PRE>
 */
package com.cogent.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.log4j.Logger;

/**
 * @author: hxh
 * @date: 2006-5-29
 */
public class HtmlUtil{
	/**数据库driver	 */
	public static final String DRIVER_ORACLE = "oracle.jdbc.OracleDriver";

    /** 日志对象 */
    private static Logger log = Logger.getLogger(HtmlUtil.class);

    /** HTML换行符 */
    private static final String HTML_NEW_LINE = "<br/>";

    /** 换行符 */
    private static final String NEW_LINE = "\r\n";
    
    /** 换行符 */
    private static final String NEW_LINE1 = "\n";

    /** 百分号常量 */
    public static final String PERCENT = "%";

    /** 双引号常量 */
    public static final String QUOTE = "\"";

    /** &号常量 */
    public static final String AMP = "&";

    /** 小于号常量 */
    public static final String LT = "<";

    /** 双引号转义字符常量 */
    public static final String QUETE_ESC = "&quot;";

    /** &号转义字符常量 */
    public static final String AMP_ESC = "&amp;";

    /** 小于号转义字符常量 */
    public static final String LT_ESC = "&lt;";

    private HtmlUtil(){
    }

    /**
     * 获取当前页面的上个页面地址
     * 
     * @param request HttpServlertRequest
     * @return String
     */
    public static String getReferer(HttpServletRequest request){
        // 标签页中的返回都统一返回至列表中
        String referer = ParamUtils.getStringToUTF8(request,"referer");
        if(HtmlUtil.isEmpty(referer)){
            referer = request.getHeader("referer");
        }

        referer = getEscapeReferer(referer);
        return referer;
    }

    /**
     * 转换特殊字符，等于号、&号
     * 
     * @param referer 请求中的上一个地址字符串
     * @return
     */
    public static String getEscapeReferer(String referer){
        if(!HtmlUtil.isEmpty(referer)){
            referer = referer.replaceAll(AMP,"_amp_");
            referer = referer.replaceAll("=","_eq_");
        }
        return referer;
    }

    /**
     * 转回特殊符号
     * 
     * @param referer
     * @return
     * @since 2006-07-27
     */
    public static String getUnEscapeReferer(String referer){
        if(!HtmlUtil.isEmpty(referer)){
            referer = referer.replaceAll("_amp_",AMP);
            referer = referer.replaceAll("_eq_","=");
        }
        return referer;
    }

    /**
     * 转回特殊符号
     * 
     * @param referer
     * @return
     * @since 2006-07-27
     */
    public static String getUnEscapeReferer(HttpServletRequest request){
        String referer = getReferer(request);
        if(!HtmlUtil.isEmpty(referer)){
            // 去掉referer前面的CMIS应用程序名，以便RequestProcessor类能正常找到Action映射
            String path = request.getContextPath();
            if(!HtmlUtil.isEmpty(path)){
                if(referer.startsWith(path)){
                    referer = referer.substring(path.length());
                }
            }
            return getUnEscapeReferer(referer);
        }
        return referer;
    }

    /**
     * 设置提示信息
     * 
     * @param request HttpServlertRequest
     * @param msg 提示信息在config.xml文件中的位置，如a.b.c
     */
    public static void setMsg(HttpServletRequest request,String msg){
        request.getSession().setAttribute("msg",Globals.getPropertyNotNull(msg));
    }

    /**
     * 设置提示信息
     */
    public static void setMessage(HttpServletRequest request,String msg){
        request.getSession().setAttribute("msg",msg);
    }

    /**
     * 获取页面提示信息
     * 
     * @param request 页面请求
     * @return String 返回提示信息
     */
    public static String getMsg(HttpServletRequest request){
        /** BEGIN** Update by Sun 2006-06-01 10:45 AM */
        /*
         * String name = (String) request.getAttribute("msg"); if (name == null)
         * return "";
         */

        // 特殊处理:弹出窗口被关闭时,由父窗口进行提示
        String responsed = (String)request.getAttribute("responsed");
        if(responsed != null)
            return "";

        Object obj = request.getSession().getAttribute("msg");
        String name = (obj == null)?"":BaseUtil.getNotNullStr((String)obj);
        if(HtmlUtil.isEmpty(name)){
            return "";
        }
        request.getSession().removeAttribute("msg");
        /** END* */

        String str = "<script type='text/javascript'>\n" + "//for functional test reason,we have to add this:\n"
            + "if(window.top.selenium){" + "  window.top.selenium.browserbot._modifyWindow(window);" + "}\n" +
            // 新模块编辑页面显示时会在页面加载后调整下拉框宽度，因此需要异步alert，否则会明显看到下拉框宽度调整的过程.
            "setTimeout(\"alert('";
        str += name + "')\",1);\n</script>";
        return str;
    }

    /**
     * 获取SQL中like子句的值
     * 
     * @param param 参数值
     * @return param为空返回"%"，不为空返回"%" + param + "%"
     */
    public static String getPercent(String param){
        if(isEmpty(param)){
            param = PERCENT;
        }else{
            param = PERCENT + param + PERCENT;
        }
        return param;
    }

    /**
     * 对字符串中的非法字符："&<进行转义
     * 
     * @param string 包含非法字符的字符串
     * @return
     */
    public static String getESC(String string){
        return string.replaceAll(QUOTE,QUETE_ESC).replaceAll(AMP,AMP_ESC).replaceAll(LT,LT_ESC);
    }

    /**
     * 确定关键字为空
     * 
     * @param someStr 关键字
     * @return 关键字为null或长度为0或值为"null"时返回true
     */
    public static boolean isEmpty(String someStr){
        return someStr == null || someStr.trim().length() == 0 || someStr.trim().equalsIgnoreCase("null");
    }

    /**
     * 确定关键字为空
     * 
     * @param someLong 关键字
     * @return 关键字为null或0时返回true
     */
    public static boolean isEmpty(Long someLong){
        return someLong == null || someLong.intValue() == 0;
    }

    /**
     * 确定为管理员
     * 
     * @param username 用户名称
     * @return
     */
    public static boolean isAdmin(String username){
        return "admin".equals(username);
    }

    public static String getForwardString(String referer,String actionName){
        if(referer.indexOf(actionName) > 0){
            String temp = referer.substring(referer.indexOf(actionName));
            temp = temp.replaceAll("_eq_","=");
            temp = temp.replaceAll("_amp_","&");

            return temp;
        }

        return "";
    }

    /**
     * 获取查看页面的“多行文本”，将内容中的"\r\n"换行符转化为HTML换行标记"<br>"
     * 
     * @param text
     */
    public static String getHtmlLine(HttpServletRequest request,String formName,String fieldName){
        // 获取Form对象
        Object formObject = request.getAttribute(formName);
        if(formObject == null)
            return "";
        try{
            String fieldValue = BeanUtils.getProperty(formObject,fieldName);
            if(isEmpty(fieldValue))
                return "";
            fieldValue = htmlEncode(fieldValue);
            return fieldValue.replaceAll(NEW_LINE,HTML_NEW_LINE);
        }catch(Exception e){
        }
        return "";
    }

    /**
     * @since 2008-08-09
     */
    public static String getHtmlLine(String value){
        if(isEmpty(value))
            return "";
        value = htmlEncode(value);
        return value.replaceAll(NEW_LINE,HTML_NEW_LINE);
    }

    /**
     * 替换敏感字符
     * 
     * @since 2006-08-16
     */
    public static String htmlEncode(String value){
        if(value == null){
            return "";
        }
        value = value.replaceAll("&","&amp;");
        value = value.replaceAll("<","&lt;");
        value = value.replaceAll(">","&gt;");
        value = value.replaceAll("\"","&quot;");
        value = value.replaceAll("'","&#146;");

        // bug229 caozheng 080521
        value = value.replaceAll("\\\\","\\\\\\\\");
        
        return value;
    }
    /**
     * 替换敏感字符.
     * 替换换行  直接在htmlEncode方法修改 会.
     * 影响其他功能.
     * @since 2008-6-11 zouwei.
     */
    public static String htmlEncodeNewline(String value){
        if(value == null){
            return "";
        }
        value = value.replaceAll("&","&amp;");
        value = value.replaceAll("<","&lt;");
        value = value.replaceAll(">","&gt;");
        value = value.replaceAll("\"","&quot;");
        value = value.replaceAll("'","&#146;");
        // zouwei 转换 换行 2008-06-11
        value = value.replaceAll("\n","&n");
        value = value.replaceAll("\r","&r");
        
        // bug229 caozheng 080521
        value = value.replaceAll("\\\\","\\\\\\\\");
        
        return value;
    }
    
    /**
     * 替换敏感字符
     * @param value
     * @return
     */
    public static String charEncode(String value) {
    	if(value == null){
            return "";
        }
    	value = value.replaceAll("&","&amp;");
        value = value.replaceAll("<","&lt;");
        value = value.replaceAll(">","&gt;");
        value = value.replaceAll("\"","&quot;");
        value = value.replaceAll("\n","&n");
        value = value.replaceAll("\r","&r");
        
    	value = value.replaceAll("\\\\","\\\\\\\\");
		value = value.replaceAll("'","&acute;");
		return value;
    }

    /**
     * 获取指定内容的省略格式，即超过指定长度后使用"..."代替
     * 
     * @param content 字符串
     * @param maxlength 最大长度
     * @return
     */
    public static String getEclipseString(String content,int maxlength){
        if(isEmpty(content))
            return "";
        if(maxlength == 0)
            maxlength = 20;
        if(content.length() > maxlength){
            content = content.substring(0,maxlength) + "...";
        }
        return content;
    }

    /**
     * 获取指定内容的省略格式，即长度超过20后使用"..."代替
     * 
     * @param content 字符串
     * @return
     */
    public static String getEclipseString(String content){
        return getEclipseString(content,0);
    }

    /**
     * 将单引号和双引号转为自定的编码（解决js方法的参数包含引号时出错,弹出窗口取返回值） "(&quot;) -> &db; , '(&#39) ->
     * &sg;
     * 
     * @return
     */
    public static String encodeQuot(String str){
        str = htmlEncode(str);
        return str.replaceAll("&quot;","&db;").replaceAll("&#146;","&sg;").replaceAll(NEW_LINE,"").replaceAll(NEW_LINE1,"");
    }

    /**
     * 获取HashMap的value值得，为空或没有时将其转换
     * 
     * @param map
     * @param key
     * @return
     */
    public static String getMapValue(Map map,String key){
        String str = "";
        if((map == null) || (key == null))
            return str;
        if(map.containsKey(key)){
            str = (String)map.get(key);
            if(str == null)
                str = "";
        }

        return str;
    }

    /**
     * @param str 参数值
     * @return str为空返回" "，不为空返回传过来的值
     */
    public static String getIsNull(String str){
        if(isEmpty(str)){
            str = " ";
        }
        return str;
    }

    /**
     * 行政区划为空就是-999
     */
    public static String getCodeValue(String str){
        if(isEmpty(str)){
            str = "-999";
        }
        return str;
    }

    /**
     * 获取远程天气数据
     */
    public static String getRemoteWeatherData(){

        // 天气数据来源
        String path = Globals.getPropertyNotNull("weather.url");

        // 天气数据内容
        String content = "";

        InputStream is = null;
        try{
            // 创建URL
            URL url = new URL(path);
            // 打开输入流

            is = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            // 只获取第一行

            content += br.readLine();

            // 转码
            content = Ascii2Native.ascii2native(content);
        }catch(Exception e){
            if(log != null)
                log.error("getRemoteWeatherData() fail.",e);
        }finally{
            try{
                if(is != null)
                    is.close();
            }catch(IOException e){
                if(log != null)
                    log.error("getRemoteWeatherData() fail.",e);
            }
        }
        return content;
    }

    /**
     * 获得填充的空白行(用于pda计生数据修改页gatherFamilyModIpt.jsp)
     * 
     * @param totalNum 总行数
     * @param realNum 实际行数
     * @param colNum 列数
     * @since 2006-10-13
     * @return
     */
    public static String getEmptyRows(int totalNum,int realNum,int colNum){
        String rows = "";
        int diff = totalNum - realNum;
        if(totalNum <= 0 || colNum <= 0 || diff <= 1){
            return rows;
        }

        for(int i = 0;i < diff - 1;i++){
            rows += "<tr>";
            for(int j = 0;j < colNum;j++){
                rows += "<td class='td_text'>&nbsp;</td>";
            }
            rows += "</tr>\n";
        }

        return rows;
    }

    /**
     * 将源对象的日期对象拷贝至目标对象
     * 
     * @param toBean 目标对象
     * @param sourceBean 源对象
     * @param propertyName 属性名称
     * @throws Exception
     */
    public static void copyDate(Object toBean,Object sourceBean,String propertyName) throws Exception{
        Date date = (Date)PropertyUtils.getProperty(sourceBean,propertyName);
        if(date != null){
            PropertyUtils.setProperty(toBean,propertyName,DateUtil.formatDate(date,"yyyy-MM-dd"));
        }
    }

    /**
     * 拷贝属性值
     * 
     * @param destBean 目标对象
     * @param oriBean 源对象
     * @param properties 属性名称数组
     * @throws Exception
     */
    public static void setProperty(Object destBean,Object oriBean,String[] properties) throws Exception{
        for(int i = 0;i < properties.length;i++){
            String property = properties[i];
            Object propertyValue = PropertyUtils.getProperty(oriBean,property);
            PropertyUtils.setProperty(destBean,property,propertyValue);
        }
    }

    /**
     * 返回集合中的对象
     * 
     * @param objects 集合
     * @param id 标识
     * @return
     * @throws Exception
     * @see EducateOLAction.saveEducate()
     */
    public static Object getObject(Set objects,Long id) throws Exception{
        for(Iterator iter = objects.iterator();iter.hasNext();){
            Object object = (Object)iter.next();
            Long tmpId = (Long)PropertyUtils.getProperty(object,"id");
            if(tmpId.equals(id)){
                return object;
            }
        }
        return null;
    }

    /**
     * 获取请求路径
     * 
     * @param request
     * @return
     */
    public static String getPath(HttpServletRequest request){
        return request.getContextPath() + "/";
    }

    /**
     * 返回列表中对象的属性值字符串
     */
    public static String getPropertyString(List list,String propertyName) throws Exception{
        StringBuffer sb = new StringBuffer();
        for(Iterator iter = list.iterator();iter.hasNext();){
            Object object = (Object)iter.next();
            Long id = (Long)PropertyUtils.getSimpleProperty(object,propertyName);
            if(sb.length() > 0){
                sb.append(",");
            }
            sb.append(id);
        }
        return sb.toString();
    }

    public static String getUTF8(String value){
        try{
            value = URLEncoder.encode(value,"UTF-8");
        }catch(UnsupportedEncodingException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 根据Map中的名值对构建XML格式的字符串，用于ajax获取结果
     * 
     * @param resultMap
     * @return "<root><item><value>111</value><text>文本</text></item></root>"
     */
    public static String getXml(Map resultMap){
        StringBuffer result = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        result.append("<root>");

        for(Iterator iter = resultMap.keySet().iterator();iter.hasNext();){
            String name = (String)iter.next();
            String value = (String)resultMap.get(name);
            result.append("<item>");
            result.append("<value>" + value + "</value>");
            result.append("<text>" + name + "</text>");
            result.append("</item>");
        }
        result.append("</root>");
        return result.toString();
    }

    /**
     * 获取option集合
     * 
     * @return "<option value='100'>文本</option>"
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static String getOption(List list,String defaultValue,String labelName,String valueName)
        throws IllegalAccessException,InvocationTargetException,NoSuchMethodException{
        StringBuffer result = new StringBuffer("");

        for(Iterator iter = list.iterator();iter.hasNext();){
            Object object = iter.next();
            String label = PropertyUtils.getProperty(object,labelName).toString();
            String value = PropertyUtils.getProperty(object,valueName).toString();
            String selectedFlag = value.equals(defaultValue)?"selected":"";
            result.append("<option value='" + value + "' " + selectedFlag + ">");
            result.append(label);
            result.append("</option>");
        }
        return result.toString();
    }
}
